#!/usr/bin/python3
import sys
import argparse

parser = argparse.ArgumentParser(description="git commit duplicate check tools")

parser.add_argument('src', help='src list file')
parser.add_argument('ref', help='reference list file')
parser.add_argument('-p', help='print duplicate lines', action='store_true')
parser.add_argument('-s', help='remove from source list', action='store_true')
parser.add_argument('-r', help='remove from reference list', action='store_true')
parser.add_argument('-o', help='output file', default=None)
parser.add_argument('-c', help='hash subject commit list format', action='store_true')

args = parser.parse_args()

src = args.src
ref = args.ref

do_print = args.p
mod_s = args.s
mod_r = args.r

print(f"Checking duplicate items in {src} with {ref}", file=sys.stderr);

sf = open(src, "rb")
rf = open(ref, "rb")

src_lines = sf.readlines()
ref_lines = rf.readlines()

rf.close()
sf.close()

dup_lines = []

for l in ref_lines:
    # print("[%s]" % l.strip())
    p = l
    if args.c:
        p = l[13:]

    #print(f"pattern: {p}")
    if p in src_lines:
        dup_lines.append(l);
        if do_print:
            dl = l.strip().decode()
            print(f"dup: {dl}")

target = None

if mod_s:
    print("Remove from src list", file=sys.stderr)
    target = src_lines
elif mod_r:
    print("Remove from ref list", file=sys.stderr)
    target = ref_lines

if target == None and args.o != None:
    print("Warning: output file set but target list is missing!", file=sys.stderr)

if target != None:
    for l in dup_lines:
        target.remove(l)

if target != None and do_print:
    for l in target:
        line = l.strip().decode()
        print(f"{line}")

if target != None and args.o != None:
    f = open(args.o, "w+")
    for l in target:
        f.write(l.decode())
    f.close()
